﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using GrailTechnology.OpenCalais;
using umbraco;

namespace GrailTechnology.AutoTags.DataType
{
    public partial class AutoTags_old : UserControl, umbraco.editorControls.userControlGrapper.IUsercontrolDataEditor
    {
        public OpenCalaisService OpenCalais
        {
            get
            {
                if (ViewState["GTAutoTagsConnection"] == null)
                {
                    ViewState["GTAutoTagsConnection"] = new OpenCalaisService();
                }

                return ViewState["GTAutoTagsConnection"] as OpenCalais.OpenCalaisService;
            }

            set { ViewState["GTAutoTagsConnection"] = value; }
        }

        private List<string> _tags = new List<string>();
        private string _umbracoValue;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                LoadUmbracoValue();
                OpenCalais = new OpenCalaisService();
                if (OpenCalais.ContainsErrors)
                {
                    DisplayErrors();
                }
                
                BindData();
            }
            else
            {
                SaveUmbracoValue();
            }
        }

        protected void ButtonFindTags_Click(object sender, ImageClickEventArgs e)
        {
            literalErrors.Text = string.Empty;
            panelErrors.Visible = false;
            updatePanelTags.Update();

            var content = GetNodePropertyValue("bodyText");
            OpenCalais.GenerateTags(content);
            if (OpenCalais.ContainsErrors)
            {
                DisplayErrors();
            }
            else
            {
                LoadUmbracoValue();
                AppendTags(OpenCalais.Tags);
            }
        }

        private void AppendTags(string tag)
        {
            if(!_tags.Contains(tag) && !Utils.IsUrl(tag))
            {
                _tags.Add(tag.Replace("_", " "));
            }
        }

        private void AppendTags(IEnumerable<string> tagList)
        {
            foreach(var str in tagList)
            {
                AppendTags(str);
            }

            BindData();
        }

        private void BindData()
        {
           // repeaterTags.DataSource = _tags;
           // repeaterTags.DataBind();
            updatePanelTags.Update();
            Session["tags"] = _tags;
        }

        private void DisplayErrors()
        {
            var sb = new StringBuilder();
            sb.Append("<ul>");
            foreach (var error in OpenCalais.Errors)
            {
                sb.AppendFormat("<li>{0}</li>", error);
            }
            sb.Append("</ul>");
            literalErrors.Text = sb.ToString();
            panelErrors.Visible = true;
            updatePanelTags.Update();
        }

        private void LoadUmbracoValue()
        {
            if (string.IsNullOrEmpty(_umbracoValue))
                Session["tags"] = null;
            else
            {
                if (_umbracoValue.Substring(_umbracoValue.Length - 1, 1) == ",")
                    _umbracoValue = _umbracoValue.Substring(0, _umbracoValue.Length - 1);

                _tags.AddRange(_umbracoValue.Split(','));
                Session["tags"] = _tags;
            }
        }

        private void SaveUmbracoValue()
        {
            var tags = (List<string>)Session["tags"];
            if (tags != null)
            {
                _umbracoValue = string.Join(",", tags.ToArray());
            }
        }

        private string GetNodePropertyValue(string propertyAlias)
        {
            string itemName = string.Format("//node[@id='{0}']/data[@alias='{1}']", Request["id"], propertyAlias);
            string data = string.Empty;
            System.Xml.XPath.XPathNodeIterator iter = library.GetXmlNodeByXPath(itemName);

            if (iter.MoveNext())
            {
                // retrieve the setting value from the InnerXml
                data = iter.Current.InnerXml;
            }

            return (data);
        }

        #region IUsercontrolDataEditor Members

        public object value
        {
            get
            {
                return _umbracoValue;
            }
            set
            {
                _umbracoValue = value.ToString();
            }
        }

        #endregion

        protected void RepeaterTags_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
        {
            _tags = Session["tags"] as List<string>;
            if (_tags != null)
            {
                var toDelete = e.CommandArgument as string;
                _tags.Remove(toDelete);
                BindData();
                SaveUmbracoValue();
            }
        }

        protected void buttonAdd_Click(object sender, EventArgs e)
        {
            if (textAddOwn.Text.Trim().Length > 0)
            {
                _tags = Session["tags"] as List<string>;
                AppendTags(textAddOwn.Text.Trim());
                BindData();
                SaveUmbracoValue();
            }
        }
    }
}